<?php

namespace app\admin\controller;

use think\Controller;
use think\Session;
use think\Db;
use think\Validate;
use app\admin\controller\Base;

class Category extends Base
{
	//显示所有的课程分类
	public function index()
	{
		$list = Db::name('category')->paginate(5);
		// dump($list);die;
		return view('category/index',[
					'title'=>'课程分类管理',
					'content'=>'课程分类表',
					'list'=>$list
				]);
	}


	//加载添加分类页面

	public function cat_add($id='0',$ppath='0,')
	{
		// dump($id);die;
       if($id=='0'){
            $path = '0,';
       }else{
            $path =  $ppath.$id.',';
       }

		header("Cache-control: private");

		// dump($path);die;
		return view('category/cat_add',[
					'title'=>'课程分类管理',
					'content'=>'添加分类',
					'pid'=>$id,
					'path'=>$path
					]);
	}


	public function doadd()
    {
        $data = input('post.');
        $namedup = Db::name('category')->where('catename',$data['catename'])->select();
        if(!empty($namedup)){
             $this->error('不能重复添加','/Cat/');
        }
        // dump($data);die;
        $rule =[
                'catename'   => 'require|regex:/^[\x{4e00}-\x{9fa5}]{2,16}$/u',
                'display'=>'require|boolean',
                'pid'=>'require|number',
                'path' =>'require'
                ];

        $message  =[
            'name.require' => '分类名必须填',
            'name.regex'     => '分类名为2-16位中文汉字',
            'display.require'   => '状态必须填',
            'display.boolean'=>'状态为显示或者隐藏',
            'pid.require'  => '父级分类ID必填',
            'pid.number'  => '父级分类ID为数字',
            'path.require'  => 'path必填',
            ];
        
        $validate = new Validate($rule,$message);
        $result   = $validate->check($data);
        if(!$result){
            $this->error($validate->getError());
        }else{
            $res =  db('Category')->insertGetId($data);
        }
        if($res){
            $this->success('新增成功', '/Cat/');
        }else{
            $this->error('新增失败','/Cat/');
        }
    }

    public function delete_cate($id)
    {
        //没有子分类 子分类下没有课程的才可以删除
        $res1 = Db::name('category')->where('pid',$id)->select();
        $res2 = Db::name('course')->where('categoryid',$id)->select();
        if(empty($res1)&&empty($res2)){
            Db::name('category')->where('id',$id)->delete();
            $this->success('删除成功', '/Cat/');
            
        }else{
            $this->error( '请先删除该分类下的子分类或者课程');
        }
    }

    public function find_cate($id,$limit=10000)
    {
        $c_two = Db::name('category')->where('pid',$id)->field('id')->select();
        $two = '';
        foreach($c_two as $k=>$v){
            $two .= ','. $v['id'];
        }
        $two .= ','.$id;
        // dump($two);die;
        $ins = substr($two,1);
        
        $c_three = Db::name('category')->where('pid','in',$ins)->field('id')->select();
        foreach($c_three as $k=>$v){
            $two .= ','.$v['id'];
        }
        
        
        $two = substr($two,1);
        return $two;
        
        
    }

    public function find_courseid($id,$limit=10000)
    {
        $two = $this->find_cate($id,$limit=10000);
        $course = Db::name('course')->alias('c')
            ->field('c.id')
            ->join('coursepicture p','p.courseid=c.id')
            ->where('c.categoryid','in',$two)
            ->where('c.display','1')
            ->where('p.cover','1')
            ->limit($limit)
            ->buildsql();
            $res = Db::query($course);
        $data = [];
        foreach($res as $k=>$v){
            $data[] = $v['id'];
        }
        return $data;
    }

    public function change_status($id,$sta)
    {
        
        $sta == 1? $sta=0:$sta=1;

        $data['display'] = $sta;

        //其他所有子分类
        $cates = $this->find_cate($id,$limit=10000);
        //所属分类下所有课程
        $courses = $this->find_courseid($id,$limit=10000);
        // dump($courses );die;
        // 开启事务
        Db::startTrans();
        try{
            // 改变用户状态
            $res1 = Db::name('category')
                ->where('id','in',$cates)
                ->update($data);

            $res2 = Db::name('course')
                ->where('id','in',$courses)
                ->update($data);

            Db::commit();
            $this->success('更改成功');
            
        }catch(Exception $exception){
            Db::rollback();
            $this->error('更改失败');
        }

    }

	
}